<template>
  <div class="source-add-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">添加新闻源</h1>
        </div>
        <div class="flex space-x-3">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSaveClick" :loading="saving">保存</el-button>
        </div>
      </div>
    </div>

    <!-- 新闻源表单 -->
    <SourceForm
      ref="sourceFormRef"
      mode="add"
      @save="handleSave"
      @cancel="handleCancel"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { sourceAPI } from '~/services/api'
import SourceForm from '~/components/admin/SourceForm.vue'

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()
const sourceFormRef = ref()
const saving = ref(false)

// 保存新闻源（表单组件调用）
const handleSave = async (formData) => {
  try {
    saving.value = true
    
    // 调用后端API添加新闻源
    const result = await sourceAPI.addSource(formData)
    
    if (result.code === 200) {
      ElMessage.success('添加新闻源成功')
      router.push('/admin/source/list')
    } else {
      ElMessage.error(result.message || '添加新闻源失败')
    }
  } catch (error) {
    console.error('添加新闻源失败:', error)
    ElMessage.error('添加新闻源失败，请重试')
  } finally {
    saving.value = false
  }
}

// 保存按钮点击事件
const handleSaveClick = () => {
  sourceFormRef.value?.handleSave()
}

// 取消操作
const handleCancel = () => {
  router.push('/admin/source/list')
}
</script>

<style scoped>
.source-add-page {
  @apply w-full;
}
</style>
